<?php  session_start();
/**
* @package		Parents@School
* @copyright	                Copyright (C) 2008 Kristof Beckers. All rights reserved.
* @Version		2.0
* @license		GNU/GPL, see LICENSE.php
**/

include ("../../include/config.php");
require_once ("../../include/db.php");
include ("../../include/header.php");
if ($_SESSION['admin'] == "$adminid"){
	
	
    function query_to_csv($conn, $query, $filename, $attachment = false, $headers = true) {
        
        if($attachment) {
            // send response headers to the browser
            header( 'Content-Type: text/csv' );
            header( 'Content-Disposition: attachment;filename='.$filename);
            $fp = fopen('php://output', 'w');
        } else {
            $fp = fopen($filename, 'w');
        }
        
        $result = mysql_query($query, $conn) or die( mysql_error( $conn ) );
        
        if($headers) {
            // output header row (if at least one row exists)
            $row = mysql_fetch_assoc($result);
            if($row) {
                fputcsv($fp, array_keys($row));
                // reset pointer back to beginning
                mysql_data_seek($result, 0);
            }
        }
        
        while($row = mysql_fetch_assoc($result)) {
            fputcsv($fp, $row);
        }
        
        fclose($fp);
    }

    // Using the function
    $sql = "SELECT * FROM $tbusers";
    // $db_conn should be a valid db handle

    // output as an attachment
    query_to_csv($conn, $sql, "users.csv", true);

    // output to file system
    query_to_csv($conn, $sql, "users.csv", false);
}
?>